package com.tomorrow.runner.test;

import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;

import com.tomorrow.runner.R;
import com.tomorrow.runner.activity.basic.BasicActivity;

import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;

public class SensorTestActivity extends BasicActivity implements SensorEventListener {

    private static final String TAG = "SensorTestActivity";
    SensorManager manager;
    List<PointValue> values_x = new ArrayList<>();
    List<PointValue> values_y = new ArrayList<>();
    List<PointValue> values_z = new ArrayList<>();
    List<PointValue> values_g = new ArrayList<>();
    float mX = 0;
    LineChartView lineChartView_x;
    LineChartView lineChartView_y;
    LineChartView lineChartView_z;
    LineChartView lineChartView_g;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sensor_test);
    }
    @Override
    protected void onResume() {
        super.onResume();
        manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        lineChartView_x = (LineChartView) findViewById(R.id.chart_x);
        lineChartView_y = (LineChartView) findViewById(R.id.chart_y);
        lineChartView_z = (LineChartView) findViewById(R.id.chart_z);
        lineChartView_g = (LineChartView) findViewById(R.id.chart_g);


        //有的手机能够获取到重力传感器
        //有的手机能够获取到加速度传感器
        //获取其中一个就可以了
        Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            manager.registerListener(this,sensor,SensorManager.SENSOR_DELAY_NORMAL,1000);
        }
        else{
            manager.registerListener(new SensorListener(){

                @Override
                public void onSensorChanged(int sensor, float[] values) {
                    showInfo(sensor,values);
                }

                @Override
                public void onAccuracyChanged(int sensor, int accuracy) {

                }
            },Sensor.TYPE_ACCELEROMETER,SensorManager.SENSOR_DELAY_NORMAL);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        //manager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        Sensor sensor = event.sensor;
        showInfo(sensor.getType(),event.values);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
    int stepCount_base = 0;
    int stepCount_up_base = 0;
    int stepCount_low_base = 0;
    long lastTimestamp = System.currentTimeMillis();
    long PERIOD = 600;//ms  一步大约需要600ms 取1/4
    final float PER = 0.5f;
    final float THRESHOLD_BASE = 1.0f;
    final float THRESHOLD_UP = THRESHOLD_BASE + PER;
    final float THRESHOLD_LOW = THRESHOLD_BASE - PER;
    float pG = SensorManager.STANDARD_GRAVITY;
    double maxG = SensorManager.STANDARD_GRAVITY;
    double minG = SensorManager.STANDARD_GRAVITY;
    private void showInfo(int sensor, float[] values){
        if (sensor == Sensor.TYPE_ACCELEROMETER){
            mX++;
            //变为绝对值
            float x = Math.abs(values[0]);
            float y = Math.abs(values[1]);
            float z = Math.abs(values[2]);
            //判断手机重力方向
            float max = getMax(x,y,z);
            float G = 0;
            String orientation = "";
            if (max ==x){
                //手机侧立
                G = x;
                orientation = "手机侧立";
            }
            if (max == y){
                //手机正立
                G = y;
                orientation = "手机正立";
            }
            if (max == z){
                //手机平放
                G = z;
                orientation = "手机平放";
            }
            //检查时间
            long period = System.currentTimeMillis() - lastTimestamp;
            if(period > PERIOD ){
                //可以检测
                if (detect(THRESHOLD_BASE)){
                    stepCount_base++;
                }
                if (detect(THRESHOLD_UP)){
                    stepCount_up_base++;
                }
                else{
                    PERIOD+=10;
                }
                if (detect(THRESHOLD_LOW)){
                    stepCount_low_base++;
                }
                else{
                    PERIOD-=10;
                }
                //重置
                lastTimestamp = System.currentTimeMillis();
                maxG = SensorManager.STANDARD_GRAVITY;
                minG = SensorManager.STANDARD_GRAVITY;
            }else{
                //上一点大于现在,正在下降
                if (pG > G){
                    //记录下降的最低点
                    if (G <= minG){
                        minG = G;
                    }
                    else{
                        //越过了波谷，将要上升
                        pG = G;
                    }
                }
                else{//正在上升
                    //记录上升的最高点
                    if (G >= maxG){
                        maxG = G;
                    }
                    else{
                        //越过了波峰，将要下降
                        pG = G;
                    }
                }
            }
            TextView textView = (TextView) findViewById(R.id.heart_detect_info_text);
            String text =orientation+"\n"+
//                    "x="+x+"\n"+
//                    "y="+y+"\n"+
//                    "z="+z+"\n"+
                    "G="+G+"\n"+
                    "maxG="+maxG+"\n"+
                    "minG="+minG+"\n"+
                    "PERIOD="+PERIOD+"\n"+
                    "THRESHOLD_BASE="+THRESHOLD_BASE+"\n"+
                    "stepCount_base="+stepCount_base+"\n"+
                    "stepCount_low_base="+stepCount_low_base+"\n"+
                    "stepCount_up_base="+stepCount_up_base;
            textView.setText(text);
            updateUI(x,y,z,G);
        }
    }

    private boolean detect(float threshold) {
        if (maxG  >= (threshold + SensorManager.STANDARD_GRAVITY)){
            if (minG <= (SensorManager.STANDARD_GRAVITY - threshold)){
                return true;
            }
        }
        return false;
    }
    private void updateUI(float ...p ) {
        float x = p[0];
        float y = p[1];
        float z = p[2];
        float G = p[3];
        if (values_x.size() > 50){
            values_x.remove(0);
        }
        //x
        values_x.add(new PointValue(mX, x));
        //In most cased you can call data model methods in builder-pattern-like manner.
        Line line_x = new Line(values_x)
                .setColor(Color.RED)
                .setCubic(true)
                .setStrokeWidth(1)
                .setPointRadius(2);
        List<Line> lines_x = new ArrayList<>();
        lines_x.add(line_x);
        LineChartData data_x = new LineChartData();
        data_x.setLines(lines_x);
        lineChartView_x.setLineChartData(data_x);
        //y
        if (values_y.size() > 50){
            values_y.remove(0);
        }
        values_y.add(new PointValue(mX, y));
        //In most cased you can call data model methods in builder-pattern-like manner.
        Line line_y = new Line(values_y)
                .setColor(Color.YELLOW)
                .setCubic(true)
                .setStrokeWidth(1)
                .setPointRadius(2);
        List<Line> lines_y = new ArrayList<>();
        lines_y.add(line_y);
        LineChartData data_y = new LineChartData();
        data_y.setLines(lines_y);
        lineChartView_y.setLineChartData(data_y);
        //z
        if (values_z.size() > 50){
            values_z.remove(0);
        }
        values_z.add(new PointValue(mX, z));
        //In most cased you can call data model methods in builder-pattern-like manner.
        Line line_z = new Line(values_z)
                .setColor(Color.BLUE)
                .setCubic(true)
                .setStrokeWidth(1)
                .setPointRadius(2);
        List<Line> lines_z = new ArrayList<>();
        lines_z.add(line_z);
        LineChartData data_z = new LineChartData();
        data_z.setLines(lines_z);
        lineChartView_z.setLineChartData(data_z);

        //G
        if (values_g.size() > 50){
            values_g.remove(0);
        }
        values_g.add(new PointValue(mX, G));
        //In most cased you can call data model methods in builder-pattern-like manner.
        Line line_g = new Line(values_g)
                .setColor(Color.GREEN)
                .setCubic(true)
                .setStrokeWidth(1)
                .setPointRadius(2);
        List<Line> lines_g = new ArrayList<>();
        lines_g.add(line_g);
        LineChartData data_g = new LineChartData();
        data_g.setLines(lines_g);
        lineChartView_g.setLineChartData(data_g);
    }

    private float getMax(float x, float y, float z) {
        float max = x;
        if (max < y){
            max = y;
        }
        if (max <z){
            max = z;
        }
        return max;
    }
}
